﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace CloudShot.Utils
{
	public static class Base64Utils
	{
		public static string SerializeToBase64(object obj)
		{
			if (obj == null)
				return null;

			// Serialize to a base 64 string
			using (MemoryStream ws = new MemoryStream())
			{
				BinaryFormatter sf = new BinaryFormatter();
				sf.Serialize(ws, obj);
				byte[] bytes = ws.GetBuffer();
				return Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None);
			}
		}

		public static object DeserializeFromBase64(string value)
		{
			if (string.IsNullOrEmpty(value))
				return null;

			// Extract data from the base 64 string!
			byte[] memorydata = Convert.FromBase64String(value);
			using (MemoryStream rs = new MemoryStream(memorydata))
			{
				BinaryFormatter sf = new BinaryFormatter();
				return sf.Deserialize(rs);
			}

		}
	}
}
